package logic

import (
	"context"
	"google.golang.org/grpc/status"
	"myMall/service/product/rpc/product"
	"myMall/service/user/model"
	"reflect"

	"myMall/service/product/rpc/internal/svc"
	"myMall/service/product/rpc/types/product_rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLogic {
	return &UpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateLogic) Update(in *product_rpc.UpdateRequest) (*product_rpc.UpdateResponse, error) {
	// 查询产品是否存在
	res, err := l.svcCtx.ProductModel.FindOne(l.ctx, in.Id)
	if err != nil {
		if err == model.ErrNotFound {
			return nil, status.Error(100, "产品不存在")
		}
		return nil, status.Error(500, err.Error())
	}

	copyNonZeroFields(res, in)

	err = l.svcCtx.ProductModel.Update(l.ctx, res)
	if err != nil {
		return nil, status.Error(500, err.Error())
	}

	return &product.UpdateResponse{}, nil
}

func copyNonZeroFields(dst, src interface{}) {
	dv := reflect.ValueOf(dst).Elem()
	sv := reflect.ValueOf(src).Elem()

	for i := 0; i < sv.NumField(); i++ {
		sf := sv.Field(i)
		df := dv.Field(i)

		zero := reflect.Zero(sf.Type()).Interface()
		if !reflect.DeepEqual(sf.Interface(), zero) {
			if df.CanSet() {
				df.Set(sf)
			}
		}
	}
}
